// list.ts - 通用任务列表页
interface Task {
  id: string
  type: string
  typeIcon: string
  typeName: string
  startLocation: string
  startAddress?: string
  endLocation: string
  endAddress?: string
  status: string
  statusText: string
  urgencyLevel: string
  urgencyText: string
  passengerCount: number
  createTime: string
  canCancel?: boolean
}

interface Stats {
  total: number
  pending: number
  inProgress: number
  completed: number
}

Page({
  data: {
    // 当前角色
    currentRole: 'user' as 'user' | 'medical' | 'driver',
    pageTitle: '我的申请',
    roleText: '用户端',
    roleInfo: {
      icon: '👤',
      name: '用户端'
    },
    
    // Tab相关
    currentTab: 'all',
    tabs: [
      { id: 'all', name: '全部任务' },
      { id: 'pending', name: '未完成' },
      { id: 'completed', name: '已完成' }
    ],
    
    // 状态栏高度和顶部总高度
    statusBarHeight: '44px',
    totalTopHeight: '176rpx',
    
    // 搜索和筛选
    searchKeyword: '',
    showFilterPanel: false,
    selectedFilters: {
      status: '',
      type: ''
    },
    
    // 任务数据
    allTasks: [] as Task[],
    filteredTasks: [] as Task[],
    
    // 统计数据
    showStats: true,
    stats: {
      total: 0,
      pending: 0,
      inProgress: 0,
      completed: 0
    } as Stats,
    
    // 状态
    loading: false,
    emptyDescription: '您还没有申请过救援服务'
  },

  /**
   * 页面加载
   */
  onLoad() {
    this.setStatusBarHeight()
    this.loadUserRole()
    this.loadTasks()
  },

  /**
   * 设置状态栏高度
   */
  setStatusBarHeight() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    
    // 计算总的顶部高度（状态栏 + 导航栏）
    // 导航栏高度是 88rpx，需要转换为px，然后再加上状态栏高度
    const navbarHeightPx = 44 // 88rpx = 44px
    const totalTopHeightPx = statusBarHeight + navbarHeightPx
    
    this.setData({
      statusBarHeight: statusBarHeight + 'px',
      totalTopHeight: totalTopHeightPx * 2 + 'rpx' // 转换为rpx单位，确保有足够的间距
    })
  },

  /**
   * 页面显示时
   */
  onShow() {
    this.loadTasks()
    
    // 更新自定义底部导航栏选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().updateSelected(0)
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadTasks()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1500)
  },

  /**
   * 加载用户角色
   */
  loadUserRole() {
    try {
      const role = wx.getStorageSync('userRole')
      const userInfo = wx.getStorageSync('userInfo')
      
      // 如果没有角色信息，跳转到登录页
      if (!role || !userInfo) {
        wx.reLaunch({
          url: '/pages/login/login'
        })
        return
      }
      
      this.setData({
        currentRole: role,
        pageTitle: this.getPageTitle(role),
        roleText: this.getRoleText(role),
        roleInfo: this.getRoleInfo(role)
      })
      
      this.updateEmptyDescription()
    } catch (e) {
      console.log('获取用户角色失败:', e)
      // 出错也跳转到登录页
      wx.reLaunch({
        url: '/pages/login/login'
      })
    }
  },

  /**
   * 获取页面标题
   */
  getPageTitle(role: string): string {
    const titleMap: Record<string, string> = {
      'user': '我的申请',
      'medical': '救援任务',
      'driver': '运输任务'
    }
    return titleMap[role] || '任务列表'
  },

  /**
   * 获取角色文本
   */
  getRoleText(role: string): string {
    const roleMap: Record<string, string> = {
      'user': '用户端',
      'medical': '医护端',
      'driver': '司机端'
    }
    return roleMap[role] || '用户端'
  },

  /**
   * 获取角色信息
   */
  getRoleInfo(role: string): { icon: string, name: string } {
    const roleInfoMap: Record<string, { icon: string, name: string }> = {
      'user': { icon: '👤', name: '用户端' },
      'medical': { icon: '🏥', name: '医护端' },
      'driver': { icon: '🚗', name: '司机端' }
    }
    return roleInfoMap[role] || { icon: '👤', name: '用户端' }
  },

  /**
   * 更新空状态描述
   */
  updateEmptyDescription() {
    const role = this.data.currentRole
    const descriptions: Record<string, string> = {
      'user': '您还没有申请过救援服务',
      'medical': '暂无待处理的救援任务',
      'driver': '暂无运输任务安排'
    }
    
    this.setData({
      emptyDescription: descriptions[role]
    })
  },

  /**
   * 加载任务数据
   */
  loadTasks() {
    this.setData({ loading: true })
    
    // 根据角色生成不同的模拟数据
    setTimeout(() => {
      const mockTasks = this.generateMockTasks()
      const stats = this.calculateStats(mockTasks)
      
      this.setData({
        allTasks: mockTasks,
        stats: stats,
        loading: false
      })
      
      this.applyFilters()
    }, 1000)
  },

  /**
   * 生成模拟任务数据
   */
  generateMockTasks(): Task[] {
    const role = this.data.currentRole
    const baseData = [
      {
        id: '001',
        type: 'ambulance',
        typeIcon: '🚑',
        typeName: '救护车',
        startLocation: '辽宁省-沈阳市',
        startAddress: '某某东大街112号院东恒生宇楼B座11.5',
        endLocation: '北京市-东城区',
        endAddress: '协和医院本部',
        status: 'pending',
        statusText: '等待接单',
        urgencyLevel: 'low',
        urgencyText: '低',
        passengerCount: 2,
        createTime: '2025-09-07 周日 09:22',
        canCancel: true
      },
      {
        id: '002',
        type: 'ambulance',
        typeIcon: '🚑',
        typeName: '救护车',
        startLocation: '辽宁省-沈阳市',
        startAddress: '某某东大街112号院东恒生宇楼B座11.5',
        endLocation: '北京市-东城区',
        endAddress: '协和医院本部',
        status: 'in_progress',
        statusText: '已发车',
        urgencyLevel: 'high',
        urgencyText: '高',
        passengerCount: 1,
        createTime: '2025-09-07 周日 09:22',
        canCancel: false
      },
      {
        id: '003',
        type: 'ambulance',
        typeIcon: '🚑',
        typeName: '救护车',
        startLocation: '辽宁省-沈阳市',
        startAddress: '某某东大街112号院东恒生宇楼B座11.5',
        endLocation: '北京市-东城区',
        endAddress: '协和医院本部',
        status: 'completed',
        statusText: '已完成',
        urgencyLevel: 'medium',
        urgencyText: '中',
        passengerCount: 3,
        createTime: '2025-09-07 周日 09:22',
        canCancel: false
      }
    ]

    // 根据角色调整状态文本
    if (role === 'medical') {
      baseData.forEach(task => {
        if (task.status === 'pending') task.statusText = '未接单'
        if (task.status === 'in_progress') task.statusText = '已发车'
        if (task.status === 'completed') task.statusText = '已完成'
      })
    } else if (role === 'driver') {
      baseData.forEach(task => {
        if (task.status === 'pending') task.statusText = '待接单'
        if (task.status === 'in_progress') task.statusText = '运输中'
      })
    }

    return baseData
  },

  /**
   * 计算统计数据
   */
  calculateStats(tasks: Task[]): Stats {
    const stats = {
      total: tasks.length,
      pending: 0,
      inProgress: 0,
      completed: 0
    }

    tasks.forEach(task => {
      switch(task.status) {
        case 'pending':
          stats.pending++
          break
        case 'in_progress':
          stats.inProgress++
          break
        case 'completed':
          stats.completed++
          break
      }
    })

    return stats
  },

  /**
   * 搜索输入
   */
  onSearchInput(e: any) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword
    })
    
    // 防抖搜索
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      this.applyFilters()
    }, 300)
  },

  /**
   * 显示筛选面板
   */
  showFilter() {
    this.setData({
      showFilterPanel: true
    })
  },

  /**
   * 隐藏筛选面板
   */
  hideFilter() {
    this.setData({
      showFilterPanel: false
    })
  },

  /**
   * 选择筛选条件
   */
  selectFilter(e: any) {
    const type = e.currentTarget.dataset.type
    const value = e.currentTarget.dataset.value
    
    this.setData({
      [`selectedFilters.${type}`]: value
    })
  },

  /**
   * 重置筛选条件
   */
  resetFilter() {
    this.setData({
      selectedFilters: {
        status: '',
        type: ''
      }
    })
  },

  /**
   * 应用筛选条件
   */
  applyFilter() {
    this.hideFilter()
    this.applyFilters()
  },

  /**
   * 切换Tab
   */
  switchTab(e: any) {
    const tabId = e.currentTarget.dataset.id
    this.setData({
      currentTab: tabId
    })
    this.applyFilters()
  },

  /**
   * 执行筛选
   */
  applyFilters() {
    const { allTasks, searchKeyword, selectedFilters, currentTab } = this.data
    
    let filtered = [...allTasks]
    
    // Tab筛选
    if (currentTab === 'pending') {
      filtered = filtered.filter(task => task.status === 'pending' || task.status === 'in_progress')
    } else if (currentTab === 'completed') {
      filtered = filtered.filter(task => task.status === 'completed')
    }
    
    // 关键词搜索
    if (searchKeyword) {
      filtered = filtered.filter(task => 
        task.typeName.includes(searchKeyword) ||
        task.startLocation.includes(searchKeyword) ||
        task.endLocation.includes(searchKeyword)
      )
    }
    
    // 状态筛选
    if (selectedFilters.status) {
      filtered = filtered.filter(task => task.status === selectedFilters.status)
    }
    
    // 类型筛选
    if (selectedFilters.type) {
      filtered = filtered.filter(task => task.type === selectedFilters.type)
    }
    
    this.setData({
      filteredTasks: filtered
    })
  },

  /**
   * 查看详情
   */
  viewDetail(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}&role=${this.data.currentRole}`
    })
  },

  /**
   * 创建新任务
   */
  createNewTask() {
    wx.navigateTo({
      url: '/pages/order/order'
    })
  },

  /**
   * 联系客服
   */
  contactService(e: any) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '客服电话',
      content: '24小时客服热线：400-123-4567\n任务ID：' + id,
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567'
          })
        }
      }
    })
    // 阻止事件冒泡到父元素
    return false
  },

  /**
   * 取消任务（用户端）
   */
  cancelTask(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('取消任务:', id)
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个救援申请吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已取消申请',
            icon: 'success'
          })
          // 这里应该调用API取消任务
          this.loadTasks()
        }
      }
    })
    return false
  },

  /**
   * 接受任务（医护端）
   */
  acceptTask(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('接受任务:', id)
    wx.showModal({
      title: '接受任务',
      content: '确认接受这个救援任务吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已接受任务',
            icon: 'success'
          })
          this.loadTasks()
        }
      }
    })
    return false
  },

  /**
   * 拒绝任务（医护端）
   */
  rejectTask(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('拒绝任务:', id)
    wx.showModal({
      title: '拒绝任务',
      content: '确定拒绝这个救援任务吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已拒绝任务',
            icon: 'none'
          })
          this.loadTasks()
        }
      }
    })
    return false
  },

  /**
   * 开始任务（医护端）
   */
  startTask(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('开始任务:', id)
    wx.showToast({
      title: '开始救援',
      icon: 'success'
    })
    this.loadTasks()
    return false
  },

  /**
   * 查看路线（司机端）
   */
  viewRoute(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('查看路线:', id)
    wx.showToast({
      title: '打开导航',
      icon: 'success'
    })
    return false
  },

  /**
   * 更新位置（司机端）
   */
  updateLocation(e: any) {
    const id = e.currentTarget.dataset.id
    console.log('更新位置:', id)
    wx.showToast({
      title: '位置已更新',
      icon: 'success'
    })
    return false
  },

  /**
   * 显示更多选项
   */
  showMore() {
    wx.showActionSheet({
      itemList: ['筛选任务', '刷新列表', '导出数据', '设置提醒'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.showFilter()
            break
          case 1:
            this.loadTasks()
            wx.showToast({
              title: '已刷新',
              icon: 'success'
            })
            break
          case 2:
          case 3:
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            })
            break
        }
      }
    })
  },

  // 防抖计时器
  searchTimer: null as any
})
